package models

import (
	"errors"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"time"
)

type Staff struct {
	Id             int    `json:"id"`
	Account        string `json:"account"`
	Mobile         string `json:"mobile"`
	Password       string `json:"-"`
	Username       string `json:"username"`
	Status         int    `json:"status"`
	Avatar         string `json:"avatar"`
	UpdatedAt      string `json:"updated_at"`
	CreatedAt      string `json:"created_at"`
	RoleId         int    `json:"role_id"`
	RoleName       string `json:"role_name"`
	DepartmentId   int    `json:"department_id"`
	DepartmentName string `json:"department_name"`
	ShopId         int    `json:"shop_id"`
	ShopName       string `json:"shop_name"`
	Supervisor     string `json:"supervisor"`
	ChiefInspector int    `json:"chief_inspector"`
	City           string `json:"city"`
}

func (u *Staff) VerifyPassword(account string, password string) (Staff, error) {
	var userInfo Staff
	err := DB.Debug().Table("staff").
		Select("staff.id,staff.account,staff.mobile,staff.password,staff.username,staff.status,staff.avatar,staff.updated_at,staff.created_at,staff.role_id,staff.department_id,staff.shop_id,department.department_name,role.role_name,shop.shop_name").
		InnerJoins("INNER JOIN department ON staff.department_id = department.id").InnerJoins("INNER JOIN role ON staff.role_id = role.id").
		InnerJoins("INNER JOIN shop ON staff.shop_id = shop.id").
		Where("staff.account = ?", account).First(&userInfo).Error
	if err != nil {
		return userInfo, errors.New("用户名或密码错误")
	}
	bytePassword := []byte(userInfo.Password)
	err = bcrypt.CompareHashAndPassword(bytePassword, []byte(password))
	if err != nil {
		return userInfo, errors.New("用户名或密码错误")
	}
	if userInfo.Status == 0 {
		return userInfo, errors.New("账号已停用")
	}
	return userInfo, nil
}

func (u *Staff) ModifyPassword(account string, newPassword string) error {
	bcryptByte, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return errors.New("加密错误，请稍候重试")
	}
	password := fmt.Sprintf("%s", bcryptByte)
	now := time.Now().Format("2006-01-02 15:04:05")
	err = DB.Table("staff").
		Where("account = ?", account).
		Update("password", password).
		Update("updated_at", now).
		Error
	if err == nil {
		return nil
	} else {
		return errors.New("保存密码失败，请稍候重试")
	}
}
